package com.tqhh.meimei.advice;

import com.alibaba.fastjson.JSON;
import com.tqhh.meimei.util.IPUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Component
@ControllerAdvice(basePackages = {"com.tqhh.meimei.controller", "com.tqhh.meimei.exception"})
@Order(0)
public class LogResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String json = JSON.toJSONString(o);
        logger.info("uri = {} | responseBody = {} | ip = {}", serverHttpRequest.getURI().getPath(), json, IPUtils.getIpAddr());
        return o;
    }
}
